'use strict';

const _ = require('lodash');
const Service = require('egg').Service;

class AtSvc extends Service {
  /**
   * 从文本中提取出@username 标记的用户名数组
   * @param {String} text 文本内容
   * @return {Array} 用户名数组
   */
  async fetchUsers(text, flag) {
    if (!text) {
      return [];
    }
    let names = text.match(/@([_a-zA-Z0-9\u4e00-\u9fa5]+)/g);
    names = [...new Set(names)].map(v => v.substr(1));
    if (flag === false) {
      return names;
    }
    let existUsers = await this.ctx.model.User.find({loginname: {'$in': names}}, {loginname: 1});
    return existUsers;
  }

  /*
   * 把@过的人缓存起来
   */
  async cacheMentionUsers(user_name, text) {
    let cacheKey = `mention:${user_name}`;
    let users = await this.fetchUsers(text);
    users = users.map(user => {
      return user.loginname;
    }).filter(user => {
      return user != user_name;
    });

    await this.service.cacheSvc.lpush(cacheKey, users);
  }

  /*
 * 从缓存中获取曾经@过的人
 */
  async getMentionUsers(user_name) {
    let cacheKey = `mention:${user_name}`;
    let result = await this.service.cacheSvc.lrange(cacheKey);
    return result;
  }

  /*
   * 根据文本内容中读取用户，并发送消息给提到的用户
   * @param {String} text 文本内容
   * @param {String} topicId 主题ID
   * @param {String} authorId 作者ID
   * @param {String} type 回复类型
   * @param {String} reply_id 回复ID
   */
  async sendMessageToMentionUsers(text, topicId, authorId, reply_id = null) {
    let users = await this.fetchUsers(text);

    users = users.filter(user => {
      return !user._id.equals(authorId);
    });

    return Promise.all(
      users.map(user => {
        return this.service.messageSvc.sendAtMessage(
          user._id,
          authorId,
          topicId,
          reply_id
        );
      })
    );
  }

  /**
   * 根据文本内容，替换为数据库中的数据
   * @param {String} text 文本内容
   * @return {String} 替换后的文本内容
   */
  async linkUsers(text) {
    const users = await this.fetchUsers(text);
    for (let i = 0; i < users.length; i++) {
      const name = users[i].loginname;
      text = text.replace(
        new RegExp(`@${name}`, 'g'),
        `[@${name}](/user/${name})`
      );
    }
    // text = text.replace(/@([_a-zA-Z0-9\u4e00-\u9fa5]+)/g, `[@$1](/user/$1)`);
    return text;
  }
}

module.exports = AtSvc;
